//! @Author: DengLibin
//! @Date: Create in 2024-07-17 16:12:32
//! @Description: 序列化函数

use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Deserializer, Serializer};
use my_util_lib::date;

/// @Author: DengLibin
/// @Date: Create in 2024-07-17 17:44:18
/// @Description: Option<DateTime<Utc>> utc时间序列化 转本地时间+8小时
pub fn serialize_date_time_utc<S>(
    date_time_o: &Option<DateTime<Utc>>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(date_time) = date_time_o {
        // 将 UTC 时间转换为中国时区的时间 +8小时
        //let sh = Tz::Asia__Shanghai;
        //let china_time = date_time.with_timezone(&sh);
        //转本地时间
        //let time_local = china_time.naive_local();

        let time_local = date_time.naive_local();
        let time_str = date::format_time(&time_local);
        return serializer.serialize_str(&time_str);
    }

    serializer.serialize_none()
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-17 17:53:04
/// @Description: 字符串日期时间转日期 字符串时间(2023-02-23 12:34:12 , )时间转utc时间
pub fn deserialize_date_time_utc<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<String> = Option::deserialize(deserializer)?;

    if let Some(value) = value {
        let date_time_utc_r = date::timestr2time_utc(&value);
        if let Ok(date_time_utc) = date_time_utc_r {
            return Ok(Some(date_time_utc));
        }
        return Err(serde::de::Error::custom("Invalid date time format"));
    }
    return Ok(None);
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-24 14:22:08
/// @Description: 时间序列化
pub fn serialize_naive_date_time<S>(
    date_time_o: &Option<NaiveDateTime>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(date_time) = date_time_o {
        let time_str = date::format_time(date_time);
        return serializer.serialize_str(&time_str);
    }

    serializer.serialize_none()
}

 /// @Author: DengLibin
 /// @Date: Create in 2024-07-24 14:28:33
 /// @Description: 时间反序列化
pub fn deserialize_naive_date_time<'de, D>(
    deserializer: D,
) -> Result<Option<NaiveDateTime>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<String> = Option::deserialize(deserializer)?;

    if let Some(value) = value {
        if let Ok(time) = date::timestr2time_naive(&value) {
            return Ok(Some(time));
        }
        return Err(serde::de::Error::custom("Invalid date time format"));
    }
    return Ok(None);
}
